<template>
  <div class="clause-select-container">
    <div class="header">
      <h2>选择条款</h2>
      <div class="back-button" @click="goBack">
        <i class="fa fa-arrow-left mr-2"></i>返回
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-indicator">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误消息 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
    </div>

    <!-- 条款列表 -->
    <div v-if="!loading && clauses.length > 0" class="clause-list-container">
      <div class="clause-list-header d-flex justify-content-between align-items-center mb-4">
        <h3>未关联到当前合同的条款 (共 {{ totalItems }} 条)</h3>
        <div class="pagination-info">
          第 {{ currentPage + 1 }} 页 / 共 {{ totalPages }} 页
        </div>
      </div>

      <ul class="list-group">
        <li
            v-for="clause in clauses"
            :key="clause.id"
            class="list-group-item d-flex justify-content-between align-items-center"
        >
          <div class="clause-item">
            <span class="clause-content">{{ clause.content }}</span>
          </div>
          <button
              @click="addClauseToContract(clause.id)"
              class="btn btn-success btn-sm"
              title="添加到合同"
          >
            <i class="fa fa-plus"></i>
          </button>
        </li>
      </ul>

      <!-- 分页控制 -->
      <div class="pagination-container mt-4">
        <button
            @click="prevPage"
            class="btn btn-secondary"
            :disabled="currentPage === 0"
        >
          <i class="fa fa-chevron-left mr-2"></i>上一页
        </button>
        <button
            @click="nextPage"
            class="btn btn-secondary"
            :disabled="currentPage === totalPages - 1"
        >
          下一页<i class="fa fa-chevron-right ml-2"></i>
        </button>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && clauses.length === 0" class="empty-message text-center py-8">
      <i class="fa fa-info-circle text-muted mr-2" style="font-size: 24px;"></i>
      <p>没有可用的未关联条款</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ClauseSelectPage',
  data() {
    return {
      contractId: null,
      clauses: [],
      totalItems: 0,
      totalPages: 1,
      currentPage: 0,
      pageSize: 10,
      errorMessage: '',
      loading: true
    }
  },
  created() {
    // 从路由参数获取合同ID
    this.contractId = this.$route.params.contractId
    if (!this.contractId) {
      this.errorMessage = '合同ID不存在'
      setTimeout(() => this.goBack(), 2000)
      return
    }
    this.fetchClauses()
  },
  methods: {
    fetchClauses() {
      this.loading = true
      axios.get(`/api/clauses/unassociated/${this.contractId}`, {
        params: {
          page: this.currentPage,
          size: this.pageSize
        }
      })
          .then(response => {
            this.clauses = response.data.content
            this.totalItems = response.data.totalElements
            this.totalPages = response.data.totalPages
          })
          .catch(error => {
            this.errorMessage = '获取条款列表失败'
            console.error('获取未关联条款错误:', error)
          })
          .finally(() => {
            this.loading = false
          })
    },

    addClauseToContract(clauseId) {
      axios.post('/api/clauses/associate', {
        contractId: this.contractId,
        clauseId: clauseId,
        type: 'INITIAL'
      })
          .then(() => {
            this.showSuccessMessage('条款添加成功')
            // 刷新当前页条款列表
            this.fetchClauses()
          })
          .catch(error => {
            this.errorMessage = '添加条款失败'
            console.error('关联条款错误:', error)
          })
    },

    prevPage() {
      if (this.currentPage > 0) {
        this.currentPage--
        this.fetchClauses()
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages - 1) {
        this.currentPage++
        this.fetchClauses()
      }
    },

    goBack() {
      this.$router.push(`/contract/create`)
    },

    showSuccessMessage(message) {
      this.errorMessage = message
      setTimeout(() => {
        this.errorMessage = ''
      }, 2000)
    }
  }
}
</script>

<style scoped>
.clause-select-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
}

.back-button {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #007bff;
  font-weight: 500;
}

.back-button:hover {
  text-decoration: underline;
}

.clause-list-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.clause-list-header {
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
  margin-bottom: 20px;
}

.pagination-info {
  font-size: 0.9rem;
  color: #6c757d;
}

.clause-item {
  flex-grow: 1;
  margin-right: 10px;
}

.clause-content {
  word-break: break-all;
  flex-grow: 1;
}

.pagination-container {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  min-height: 300px;
}

.spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #007bff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-message {
  color: #721c24;
  background-color: #f8d7da;
  border-left: 4px solid #f5c6cb;
  padding: 12px 15px;
  border-radius: 0 4px 4px 0;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.empty-message {
  color: #6c757d;
  font-style: italic;
  padding: 30px 0;
  text-align: center;
  border: 1px dashed #dee2e6;
  border-radius: 4px;
}

.btn {
  padding: 8px 15px;
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: none;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-success {
  background-color: #28a745;
  color: white;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.list-group {
  list-style: none;
  padding: 0;
  margin: 0;
}

.list-group-item {
  padding: 12px 15px;
  border: 1px solid #e9ecef;
  margin-bottom: -1px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-group-item:first-child {
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}

.list-group-item:last-child {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
}
</style>